{% extends "adibilisadminBundle::layout.html.twig" %}
     
{% block title %}
    Liste des activités - {{ parent() }}
{% endblock %}

{% block adibilisadmin_body %}


{% if app.session.hasFlash('info') %}
    <div class="alert alert-success">
        {{ app.session.flash('info') }}
    </div>
{% endif %}


<!-- Start welcome-message -->           
<section class="welcome-message">
    <div class="container">
        <div class="hero-unit">
             <h4>Activités proches<br> <small>Vous pouvez voir la liste des activités les plus proches.</small></h4>

        </div>
    </div>
</section>
<!-- End welcome-message -->

<!--  <h1>{{ 'activite.index.title'|trans }}</h1> -->
    <hr />





<div id="container">
  <div id="header">
  <p hidden id ="plat">lat</p>
  <p hidden id ="plon">long</p>
  <div id="search"></div>
	<div class="row">
        <div class="span5">
  
				<div id="utility">
				
				
				
					<ul id="list">
					{% for activite in activites %}

					<li><a class='loc' name='{{ activite.name }}' address='{{ activite.address }}' category=
					
					{% for category in activite.categories %}
					{{ category.name }} -
					{% endfor %}
					
					locality='{{ activite.locality.locality }}' 
					npa='{{ activite.locality.npa }}' 
					lat='{{ activite.latitude }}' 
					long='{{ activite.longitude }}'  
					href="{{ path('adibilisadmin_voir', { 'id': activite.id }) }}">
					{% for category in activite.categories %}
						{{ category.name }} -
					{% endfor %}
					<b>{{ activite.name }}  </b>
					 
					</a></li> 

					
					
					{% endfor %}
					</ul>
				
				</div>
			</div>
			<div class="span7">
				<div id="map_canvas" style="width:100%; height:360px !important;"></div><br/>
			</div>
    </div>
  </div>
  

  
</div>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>

var x=document.getElementById("demo");

	window.onload = getLocation;
    function getLocation()
    {
		var x=document.getElementById("demo");
		if (navigator.geolocation)
        {
		
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        }
        else{x.innerHTML="Geolocation is not supported by this browser.";}
    }
	
    function showPosition(position)
    {
		//alert('showposition');
		
		var liens = document.getElementsByClassName('loc');
		var loc = new Array(liens.length);	
		var xlat=document.getElementById("plat");
				var xlon=document.getElementById("plon");
				xlat.innerHTML=position.coords.latitude;
				xlon.innerHTML=position.coords.longitude;
		
        //alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude); 
       
        for (var i = 0; i < liens.length; i++) {
			loc[i] = new Array(8);
            var latitude = liens[i].getAttribute("lat");
            var longitude = liens[i].getAttribute("long");
            var dist = getDistanceFromLatLonInKm(position.coords.latitude, position.coords.longitude, latitude, longitude);
            
            //liens[i].innerHTML = dist+ " - " +liens[i].innerHTML;
            //sortList();
			loc[i][0]=dist;
			loc[i][1]=liens[i].innerHTML;
			loc[i][2]=liens[i].getAttribute("href");
			//loc.sort(function(a,b){return a-b});
        }
		
		
		//loc.sort(function(a,b){return a-b});
		loc.sort(mySorting);
		function mySorting(a,b) {
			a = a[0];
			b = b[0];
			return a == b ? 0 : (a < b ? -1 : 1)
		}
		
		
        for (var i = 0; i < liens.length; i++) {
			if (loc[i][0]<1)
			{
				loc[i][0] = loc[i][0]/1000.0 
				loc[i][0]=parseFloat(loc[i][0]).toFixed(2);
				loc[i][0]=loc[i][0]+ " m";
			}
			else
			{
				loc[i][0]=parseFloat(loc[i][0]).toFixed(2);
				loc[i][0] = loc[i][0]+ " km";

			}
			liens[i].innerHTML = "<b>"+loc[i][0]+ "</b> - " +loc[i][1];
			//alert(loc[i][2]);
			liens[i].setAttribute("href", loc[i][2]);
		}
		
		
        function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
        var R = 6371; // Radius of the earth in km
        var dLat = deg2rad(lat2-lat1);  // deg2rad below
        var dLon = deg2rad(lon2-lon1); 
        var a = 
            Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2)
            ; 
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        var d = R * c; // Distance in km
        
                 
            return d;
        
        
        }

        function deg2rad(deg) {
          return deg * (Math.PI/180)
        }
        
        function sortList()
		{
			// Get the ul object
			var oUl = document.getElementById("list");
			/* Perform a Bubble Sort on the list items */
			for(var i in oUl.childNodes)
			{
				var x = oUl.childNodes[i];
				for(var j in oUl.childNodes)
				{
					var y = oUl.childNodes[j];
					if((x.innerText != 'undefined' || y.innerText != 'undefined')  && x.innerText>y.innerText)
					{
						// Skip if x is already the first list item
						if(oUl.firstChild!=x)
							oUl.insertBefore(y,x);
					}
				}
			}
		 
		}
        
    }
    function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
    
   
</script>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
    <script>
 	// Set the Map variable
      	
				
      	function initializenear() {	
            var myOptions = {
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
		
		var liens = document.body.getElementsByClassName('loc');
		var actualLatitude;
		var actualLongitude;
		var locations = new Array(liens.length);
		
		for (var i = 0; i < liens.length; i++) 
		{
			locations[i] = new Array(7);
		}
		
		
		for (var i = 0; i < liens.length; i++) {
		 
			
			locations[i][0]= liens[i].getAttribute("name");
			locations[i][1]= liens[i].getAttribute("address");
			locations[i][2]= liens[i].getAttribute("locality");
			locations[i][3]= liens[i].getAttribute("href");
			locations[i][4]= liens[i].getAttribute("npa");
			locations[i][5]= liens[i].getAttribute("lat");
			locations[i][6]= liens[i].getAttribute("long");
			
				
			
			
		}		
        var all = [
            ["Location 1", "Summerdale Rd", "Elon", "NC", "27253", "36.150491", "-79.5470544"], 
            ["Location 2", "7205 Olmstead Dr", "Burlington", "NC", "27215", "36.069974", "-79.548101"],
            ["Location 3", "W Market St", "Graham", "NC", "27253", "36.0722225", "-79.4016207"],
            ["Location 4", "Mt Hermon Rock Creek Rd", "Graham", "NC", "27253", "35.9826328", "-79.4165216"],
            ["Location 5", "415 Spring Garden St", "Greensboro", "NC", "27401", "36.06761", "-79.794984"]
      	];							
        var infoWindow = new google.maps.InfoWindow;
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        // Set the center of the map
		
		var pos = new google.maps.LatLng(46.2827546, 7.5383391);
		
		if (navigator.geolocation)
		{
			navigator.geolocation.getCurrentPosition(showMapPosition);
		}
		
		
        function infoCallback(infowindow, marker) { 
            return function() {
            infowindow.open(map, marker);
        };
   }	
   
	function showMapPosition(position)
	{
		//alert("Map :"+position.coords.latitude+" " +position.coords.longitude);
		pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
		map.setCenter(pos);
		var img = "/adibilis/web/img/marker.png";
		var marker = new google.maps.Marker({  
              map: map,  title: "Position actuelle",  position: pos, icon:img
            });
		
		actualLatitude=position.coords.latitude;
		actualLongitude=position.coords.longitude;
		 
	}  

   function setMarkers(map, all) {	
	
	
   	for (var i in all) {										
            var name 	= all[i][0];
            var address = all[i][1];
            var city 	= all[i][2];
            var state 	= all[i][3];
            var zip 	= all[i][4];
            var lat 	= all[i][5];
            var lng 	= all[i][6];
            var latlngset;
            latlngset = new google.maps.LatLng(lat, lng);
            var marker = new google.maps.Marker({  
              map: map,  title: city,  position: latlngset
            });
			
			//alert(actualLatitude+" "+actualLongitude);
			//navigator.geolocation.getCurrentPosition(showMapLatitude);
			//alert(actualLatitude);
			
			//alert(position.coords.latitude);
			//alert(test);
			
			var xlat=document.getElementById("plat");
			var xlon=document.getElementById("plon");
			var linkLat= xlat.innerHTML;
			var linkLon= xlon.innerHTML;
			
            var content = '<div class="map-content"><a href="'+state+'"><b>' + name + '</b></a><br />' + address + '<br />' + zip + ',  ' + city + '<br /><a href="http://maps.google.com/?saddr='+linkLat+', '+linkLon+'&daddr=' + address + ' ' + zip + ', ' + city + '" target="_blank">Localisation</a></div>';					
            var infowindow = new google.maps.InfoWindow();
              infowindow.setContent(content);
              google.maps.event.addListener(
                marker, 
                'click', 
                infoCallback(infowindow, marker)
              );
          }
        }	
				
		
        
		window.setTimeout(setMarkers,1000, map, locations);
		
        //setMarkers(map, locations);
      };
      // Initializes the Google Map
      google.maps.event.addDomListener(window, 'load', initializenear);
	  
	  
	  
    </script>


<script>
(function ($) {
  // custom css expression for a case-insensitive contains()
  jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
  };

  function listFilter(search, list) { // header is any element, list is an unordered list
    // create and add the filter form to the header
	
	{% if app.request.locale == 'fr' %}
	var i =0;
	var cat = new Array();
		{% for category in categories %}
			cat[i] = "{{category.name}}" ;
			i=i+1;
		{% endfor %}
	{% endif %}
	{% if app.request.locale == 'en' %}
		var i =0;
		var cat = new Array();
		{% for category in categories %}
			cat[i] = "{{category.nameen}}" ;
			i=i+1;
		{% endfor %}
	{% endif %}
	{% if app.request.locale == 'de' %}
		var i =0;
		var cat = new Array();
		{% for category in categories %}
			cat[i] = "{{category.namede}}" ;
			i=i+1;
		{% endfor %}
	{% endif %}
	i =0;

	
	
	//alert(cat);
    var form = $("<form>").attr({"class":"filterform","action":"#"});
    var input = $("<select>");
	input.append('<option value=m>Tous</option>');
	var i =0;
	{% for category in categories %}
		input.append('<option value='+cat[i]+'>'+cat[i]+'</option>');
		i=i+1;
	{% endfor %}
	
    $(form).append(input).appendTo(search);

    $(input)
      .change( function () {
        var filter = $(this).val();
        if(filter) {
          // this finds all links in a list that contain the input,
          // and hide the ones not containing the input while showing the ones that do
          $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
          $(list).find("a:Contains(" + filter + ")").parent().slideDown();
        } else {
          $(list).find("li").slideDown();
        }
        return false;
      })
    .keyup( function () {
        // fire the above change event after every letter
        $(this).change();
    });
  }


  //ondomready
  $(function () {
    listFilter($("#search"), $("#list"));
  });
}(jQuery));
</script>


{% endblock %}